package com.book.service.impl;

import com.book.entity.BookInfo;
import com.book.mapper.BookInfoMapper;
import com.book.service.BookInfoService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.util.StringUtil;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author SuperYu  2024/6/14
 */
@Service
public class BookInfoServiceImpl implements BookInfoService {

    @Resource
    BookInfoMapper bookInfoMapper;


    @Override
    public List<BookInfo> findAllBookInfo() {

        return bookInfoMapper.selectAll();
    }

    @Override
    public PageInfo<BookInfo> findBookByPage(int pageNum, int pageSize) {
        Page<BookInfo> page = PageHelper.startPage(pageNum, pageSize);
        bookInfoMapper.selectAll();
        return page.toPageInfo();
    }

    @Override
    public BookInfo findBookInfoById(int id) {
        return bookInfoMapper.selectByPrimaryKey(id);
    }

    @Override
    public BookInfo findBookInfoByName(String name) {
        Example example = new Example(BookInfo.class);
        // 创建查询规则
        Example.Criteria c = example.createCriteria();
        c.andEqualTo("bookName", name);

        return bookInfoMapper.selectOneByExample(example);
    }

    @Override
    public List<BookInfo> findBookInfoLikeName(String name) {
        Example example = new Example(BookInfo.class);
        // 创建查询规则
        Example.Criteria c = example.createCriteria();
        c.andLike("bookName", "%" + name + "%");

        return bookInfoMapper.selectByExample(example);
    }

    @Override
    public List<BookInfo> findBookInfoByCondition(BookInfo bookInfo, double endPrice) {

        Example example = new Example(BookInfo.class);
        Example.Criteria c = example.createCriteria();
        // 添加名字的规则：
        if (bookInfo.getBookName() != null && bookInfo.getBookName().length() != 0) {
            c.andLike("bookName", "%" + bookInfo.getBookName() + "%");
        }
        // 添加价格规则
        if (bookInfo.getBookPrice() != null && bookInfo.getBookPrice().doubleValue() != 0) {
            c.andBetween("bookPrice", bookInfo.getBookPrice(), endPrice);
        }

        // 设置排序的字段
        example.setOrderByClause("book_price desc");

        List<BookInfo> list = bookInfoMapper.selectByExample(example);


        return list;
    }
}
